package com.zzz.gp.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.zzz.gp.bean.Gp;
import com.zzz.gp.bean.GpHistory;
import com.zzz.gp.bean.vo.GpQuery;
import com.zzz.gp.dao.GpMapper;
import com.zzz.gp.service.analyse.ADailyLimit1Service;
import com.zzz.gp.service.analyse.LPService;
import com.zzz.gp.service.analyse.RiseProportionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @description:
 * @author: ZZZ
 * @time: 2021/12/6 14:16
 */
@Slf4j
@Component
public class GpHistoryService {
    @Autowired
    private ADailyLimit1Service aDailyLimit1Service;
    @Autowired
    private LPService lp;
    @Autowired
    private RiseProportionService riseProportionService;
    @Autowired
    private GpMapper gpMapper;

    private Set<String> set = new HashSet<>();

    @Scheduled(cron = "0 0 18 * * ?")
    public void cleanSet() {

        set.clear();
        gpMapper.cleanGpHistory2();
    }

    @PostConstruct
    public void init() {
        set = gpMapper.getSetCode();
    }


    @Async("myAsync")
    public void batch2(GpQuery gpQuery) {
        log.info("=================getHistory start===============");
        int n = 0;
        List<Gp> gpList = gpMapper.getCode();
        if (gpList != null && gpList.size() > 0) {
            for (Gp x : gpList) {
                n++;
                if (set.contains(x.getCode())) {
                    gpMapper.historyExitInsert(x.getCode());
                    continue;
                }
                List<GpHistory> batch = new ArrayList<>();
                String code = x.getCode();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);

                }
                String result = "";

                String url = String.format("https://q.stock.sohu.com/hisHq?code=cn_%s&start=%s&end=%s", code, gpQuery.getStartDate(), gpQuery.getEndDate());

                boolean mark = true;
                int k = 0;
                while (mark) {
                    k++;
                    try {
                        //result = HttpRequestUtil.httpRequest(url);
                        result = HttpUtil.createGet(url).execute().body();
                    } catch (Exception e) {
                        log.error("异常：GP获取出现异常 k={}", k);
                        log.error("地址：{}", url);
                        if (k > 5) {
                            log.error(result);
                            mark = false;
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException ee) {
                            throw new RuntimeException(ee);
                        }
                    }
                    if (result.length() > 0) {
                        mark = false;
                    }

                    if (k > 5) {
                        mark = false;
                        log.error("GP多次获取失败");
                        log.error("地址：{}", url);
                        log.error("结果：{}", result);
                    }

                }

                if (result.length() > 30) {
                    log.info("============={}==============", n);
                    List<Map<String, Object>> hqList = new ArrayList<>();
                    hqList = JSONObject.parseObject(result, List.class);
                    String status = hqList.get(0).get("status").toString();
                    if ("0".equals(status)) {
                        String hq = hqList.get(0).get("hq").toString();
                        //hq = hq.substring(1, hq.length() - 1);
                        //List<String> list = JSONObject.parseObject(hq, List.class);
                        try {

                            List<List<String>> listAll = JSONObject.parseObject(hq, List.class);
                            for (List<String> list : listAll) {
                                String day1 = list.get(0);
                                String open = list.get(1);
                                String close = list.get(2);
                                String increase = list.get(3);
                                String increase_p = list.get(4);
                                increase_p = increase_p.substring(0, increase_p.length() - 1);
                                String low = list.get(5);
                                String high = list.get(6);
                                String volume = list.get(7);
                                String money = list.get(8);
                                String rate = list.get(9);
                                if (rate.endsWith("%")) {
                                    rate = rate.substring(0, rate.length() - 1);
                                } else {
                                    rate = "100";
                                }

                                String name = x.getName();

                                GpHistory history = new GpHistory(code, name, open, close, increase, increase_p, low, high, volume, money, rate, day1);
                                batch.add(history);
                            }
                            if (batch.size() > 0) {
                                //log.info("开始插入数据 {} 条 {}", batch.size(), n);
                                gpMapper.historyBatchInsert(batch);
                                gpMapper.historyBatchInsert2(batch);
                                set.add(x.getCode());
                            }
                        } catch (Exception e) {
                            log.error("格式转换异常：{}", e.getMessage());
                        }
                    }
                }


            }

            lp.init();
            aDailyLimit1Service.init();
            riseProportionService.todayRiseProportionSum();
        }

        log.info("=================getHistory success===============");
    }


}
